#!/bin/bash
path="";
moduleName="";
email="";
message=""
countLimit=10
sizeLimit=0   #单位KB
totalSizeLimit=100   #单位KB
thisModuleExceed=0
totalSize=0
outpufile=""
rootdir=""

while getopts "p:m:o:e:c:d:s:t:" arg
do
    case $arg in
        p)
            path=$OPTARG;;
        m)
			moduleName=$OPTARG;;
		e)
			email=$OPTARG;;
	  o)
			outpufile=$OPTARG;;
		c)
			countLimit=$OPTARG;;
    d)
			rootdir=$OPTARG;;
		s)
			sizeLimit=$OPTARG;;
		t)
            totalSizeLimit=$OPTARG;;
    esac
done

if [ -z "$moduleName" ]; then
	echo 'moduleName can not be empty'
	exit
fi

moduleName_low=$(echo $moduleName | tr 'A-Z' 'a-z')

echoRed(){
	echo -e "\033[0;31m${1}\033[0m";
}

getFileSize(){
	wc -c < ${1} | sed 's/ //g'
}

getSizeStr(){
	size=$1;
	if [ $size -lt 1024 ]; then
		echo "${size}B"
	elif [ $size -lt $((1024*1024)) ]; then
		echo `echo "scale=2;${size}/1024" | bc`KB
	else
		echo `echo "scale=2;${size}/1024/1024" | bc`MB
	fi
}

echo -e "start scan image, moduleName:${moduleName}, totalSizeLimit:${totalSizeLimit}KB\n"
cd $path

#check image count
count=`ls ./drawable*/jsbundles_${moduleName_low}_* | wc -l | sed 's/ //g'`
#if [ $count -gt $countLimit ]; then
#	thisModuleExceed=1;
#	limit_message="image count exceed limit, count:${count}, limit:${countLimit}<br/>"
#	message=$message$limit_message
#	echo -e "image count exceed limit, count:${count}, limit:${countLimit}\n"
#fi

#check every image size
echo "images exceed limit:"
for file in `find ./drawable*/jsbundles_${moduleName_low}_*`; do
	size=$(getFileSize $file)
	totalSize=$(($totalSize+$size))
	sizeStr=$(getSizeStr $size)
	if [ $size -gt $((sizeLimit*1024)) ]; then
		thisModuleExceed=1;
		temp_message="${file}, size:${sizeStr}<br/>";
		message=$message$temp_message;
		echo -e $temp_message;
	fi
done
if [ $totalSize -gt $((totalSizeLimit*1024)) ]; then
	thisModuleExceed=1;
	totalSizeStr=$(getSizeStr $totalSize)
	temp_message="totalSize:${totalSizeStr}<br/>";
	message=$message$temp_message;
	echo -e $temp_message;
else
    thisModuleExceed=0;
    totalSizeStr=$(getSizeStr $totalSize)
    echo "totalSize:${totalSizeStr} < ${totalSizeLimit}KB!!!"
    exit 0;
fi

 #send mail to users
if [ -n "$message" ]; then
	subject="The number of business images named ${moduleName} exceeds the standard."
    message_warning="<h1 style=\"color:red\">Warning</h1><br/>";
    message=$message_warning$message;
	python ../scripts/auto-send-mail.py -s "$subject" -m "$message" -e "$email";
fi
echo "rootdir=$rootdir"
cd $rootdir
echo "bundle_size=$totalSize"
echo "bundle_outpufile=$outpufile"
echo "bundle_size=$totalSize" >> $outpufile
cd - > /dev/null
exit $thisModuleExceed